package com.xg.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xg.frame.log.annotation.LogAnnotation;
import com.xg.sys.dto.SysDictionaryDTO;
import com.xg.sys.entity.SysDictionary;
import com.xg.sys.service.SysDictionaryService;
import com.xg.sys.vo.PageVO;
import com.xg.sys.vo.SysDictionaryVO;
import com.xg.utils.DDDUtils;
import com.xg.frame.constant.SysConstant;
import com.xg.frame.constant.UrlConstant;
import com.xg.frame.entity.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author tzt
 * @date Created in 2021/8/10 16:51
 * @description：字典管理
 * @modified By：
 */
@Slf4j
@Api(tags = "数据字典管理")
@Controller
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/dic")
public class DictionaryController {
    @Resource
    private SysDictionaryService sysDictionaryService;

    @ResponseBody
    @ApiOperation("数据字典列表查询")
    @ApiImplicitParam(paramType = "path", name = "classCode", value = "字典编码", required = true, dataType = "String")
    @PostMapping("/dicList/{classCode}")
    public R<List<SysDictionaryVO>> getDicList(@PathVariable("classCode") @NotBlank String classCode) throws Exception {
        List<SysDictionary> list = sysDictionaryService.getDiclist(classCode);
        return R.ok().info(DDDUtils.collection(list, SysDictionaryVO.class));
    }

    @GetMapping
    public String index(Model model) throws Exception {
        return "/sys/dictionary/list";
    }

    @GetMapping(value = "query")
    @ResponseBody
    public PageVO<SysDictionaryVO> query(String classCode, String className, String status, Page<SysDictionary> page) throws Exception {
        page = sysDictionaryService.page(
                page,
                new LambdaQueryWrapper<SysDictionary>()
                        .like(StringUtils.isNotEmpty(classCode), SysDictionary::getClassCode, classCode)
                        .like(StringUtils.isNotEmpty(className), SysDictionary::getClassName, className)
                        .eq(StringUtils.isNotEmpty(status), SysDictionary::getStatus, status)
                        .orderByAsc(SysDictionary::getClassCode, SysDictionary::getDataOrder)
        );
        return new PageVO<SysDictionaryVO>()
                .setTotal(page.getTotal())
                .setRows(DDDUtils.collection(page.getRecords(), SysDictionaryVO.class));
    }

    @GetMapping(value = "edit")
    public String edit(Model model, Long id) {
        SysDictionaryVO dictionaryVO = new SysDictionaryVO();
        if (Objects.isNull(id)) {
            dictionaryVO.setStatus(SysConstant.STATUS_Y);
            model.addAttribute("title", SysConstant.ADD);
        } else {
            SysDictionary byId = sysDictionaryService.getById(id);
            BeanUtils.copyProperties(byId, dictionaryVO);
            model.addAttribute("title", SysConstant.EDIT);
        }
        model.addAttribute("dictionary", dictionaryVO);
        return "/sys/dictionary/edit";
    }

    @LogAnnotation(module = UrlConstant.sysCenter, describe = "字典新增修改")
    @RequiresPermissions("dic:save")
    @PostMapping("save")
    @ResponseBody
    @CacheEvict(value = {SysConstant.CATCHE_SYS_DIC}, key = "#dictionaryVO.classCode")
    public R save(SysDictionaryVO dictionaryVO, Model model) {

        //校验字典编码开头
        if (dictionaryVO.getDataCode().startsWith(dictionaryVO.getClassCode())) {
            //校验字典编码重复
            List<SysDictionary> diclist = sysDictionaryService.getDiclist(dictionaryVO.getClassCode());
            for (SysDictionary dic : diclist) {
                if (dic.getDataCode().equals(dictionaryVO.getDataCode())) {
                    return R.error().message("已存在相同字典编码！");
                }
            }
        } else {
            return R.error().message("字典编码必须以类型编码开头！");
        }

        SysDictionaryDTO dictionaryDTO = new SysDictionaryDTO();
        BeanUtils.copyProperties(dictionaryVO, dictionaryDTO);
        //校验通过，执行保存/修改
        if (Objects.isNull(dictionaryVO.getId())) {
            sysDictionaryService.insert(dictionaryDTO);
            return R.ok().message("保存成功！");
        } else {
            sysDictionaryService.update(dictionaryDTO);
            /*sysDictionaryService.update(
                    new LambdaUpdateWrapper<SysDictionary>()
                            .eq(SysDictionary::getId, dictionaryVO.getId())
                            .set(SysDictionary::getClassCode, dictionaryVO.getClassCode())
                            .set(SysDictionary::getClassName, dictionaryVO.getClassName())
                            .set(SysDictionary::getDataCode, dictionaryVO.getDataCode())
                            .set(SysDictionary::getDataName, dictionaryVO.getDataName())
                            .set(SysDictionary::getDataOrder, dictionaryVO.getDataOrder())
                            .set(SysDictionary::getStatus, dictionaryVO.getStatus())
            );*/
            return R.ok().message("修改成功！");
        }
    }

    @LogAnnotation(module = UrlConstant.sysCenter, describe = "字典删除")
    @RequiresPermissions("dic:del")
    @GetMapping("del")
    @ResponseBody
    public R del(@NotBlank String id) {
        String[] ids = id.split(",");
        List<Long> idList = Arrays.stream(ids).map(item -> Long.parseLong(item)).collect(Collectors.toList());
        idList.forEach(delId-> sysDictionaryService.delete(sysDictionaryService.getById(delId)));
        return R.ok();
    }
}

